package com.gsmr.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.gsmr.entity.FACCH;
import com.gsmr.entity.PageBean;
import com.gsmr.entity.SDCCH;
import com.gsmr.entity.SDCCH_FACCH;
import com.gsmr.service.FACCHService;
import com.gsmr.service.InterferenceQueryService;
import com.gsmr.service.SDCCHService;
import com.gsmr.service.TCHService;
import com.gsmr.util.DateUtil;
import com.gsmr.util.ExcelUtil;
import com.gsmr.util.FormatDate;
import com.gsmr.util.ResponseUtil;
import com.gsmr.util.StringUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * SDCCH_FACCH Controller层
 * 
 * @author user
 *
 */
@Controller
@RequestMapping("/sdcch_facch")
public class SDCCH_FACCHController {
	@Resource
	private TCHService tchService;

	@Resource
	private SDCCHService sdcchService;
	
	@Resource
	private InterferenceQueryService interferencequeryService;
	
	@Resource
	private FACCHService facchService;
	
	List<SDCCH_FACCH> sdcch_facchList;
	/**
	 * 分页条件查询SDCCH
	 */
	@RequestMapping("/list")
	public void list(@RequestParam(value = "page", required = false) String page, @RequestParam(value = "rows", required = false) String rows,
			@RequestParam(value = "startTime", required = false) String startTime, @RequestParam(value = "endTime", required = false) String endTime,
			@RequestParam(value = "IMSI", required = false) String IMSI, @RequestParam(value = "MSISDN", required = false) String MSISDN,
			@RequestParam(value = "CTCS_ID", required = false) String CTCS_ID, @RequestParam(value = "UmType", required = false) String UmType,
			@RequestParam(value = "district", required = false) String district, @RequestParam(value = "kilometerStart", required = false) String kilometerStart,
			@RequestParam(value = "kilometerEnd", required = false) String kilometerEnd, @RequestParam(value = "search", required = false) String search,
			@RequestParam(value = "increase", required = false) String increase, @RequestParam(value = "recordId", required = false) String recordId,
			HttpServletResponse response) throws Exception {
		if (search == null) return;

		PageBean pageBean = new PageBean(Integer.parseInt(page), Integer.parseInt(rows));
		Map<String, Object> map = new HashMap<String, Object>();
		//map.put("FrontProcessorId", StringUtil.formatLike(sdcch.getFrontProcessorId())); // 查询SDCCH名获取
		String IMSI1 = "1";
		String IMSI2 = "1";
		String MSISDN1 = "1";
		String MSISDN2 = "1";
		List<String> traindata = new ArrayList<>();
		map.put("table_name", "train_info");
		if(!IMSI.equals("")) {
			IMSI1 = IMSI;
			map.put("IMSI", IMSI1);
			traindata = tchService.get_msisdn(map);
			if(traindata.size() != 0) {
				MSISDN1 = traindata.get(0);
			}
			CTCS_ID = "1";
		}
		else if(!MSISDN.equals("")) {
			MSISDN1 = MSISDN;
			map.put("MSISDN", MSISDN1);
			traindata = tchService.get_imsi(map);
			if(traindata.size() != 0) {
				IMSI1 = traindata.get(0);
			}
			CTCS_ID = "1";
		}
		else if(!CTCS_ID.equals("")) {
			map.put("CTCS_ID", CTCS_ID);
			traindata = tchService.get_imsi(map);
			if(traindata.size() >= 2) {
				IMSI1 = traindata.get(0);
				IMSI2 = traindata.get(1);
			}
			else if(traindata.size() == 1) {
				IMSI1 = traindata.get(0);
			}
			traindata = tchService.get_msisdn(map);
			if(traindata.size() >= 2) {
				MSISDN1 = traindata.get(0);
				MSISDN2 = traindata.get(1);
			}
			else if(traindata.size() == 1) {
				MSISDN1 = traindata.get(0);
			}
		}
		map.put("IMSI1", IMSI1);
		map.put("IMSI2", IMSI2);
		map.put("MSISDN1", MSISDN1);
		map.put("MSISDN2", MSISDN2);
		map.put("CTCS_ID", CTCS_ID);
		map.put("UmTypeAll", UmType);
		map.put("districtAll", district);
		map.put("kilometerStart", kilometerStart);
		map.put("kilometerEnd", kilometerEnd);
		map.put("recordId", recordId);

		Map<String, List<String>> tables = findTableNames(UmType, startTime, endTime, district, map);
		List<String> table_names_sdcch = tables.get("table_names_sdcch");
		List<String> table_names_facch = tables.get("table_names_facch");
		
		List<SDCCH> sdcchList = new ArrayList<>();
		List<FACCH> facchList = new ArrayList<>();
		sdcch_facchList = new ArrayList<>();

		if (table_names_sdcch != null && table_names_sdcch.size() > 0) {
			map.put("start", 0);
			map.put("size", pageBean.getPageSize());
			if (increase.equals("1")) {
				for(int i=table_names_sdcch.size()-1;i>=0&&sdcchList.size() <pageBean.getPageSize();i--) {
					String tableName = table_names_sdcch.get(i);
					map.put("table_name", tableName);
					List<SDCCH> sub_sdcchList = sdcchService.findASC(map);
					sdcchList.addAll(sub_sdcchList);
				}
			} else {
				for (int i = 0; i < table_names_sdcch.size() && sdcchList.size() < pageBean.getPageSize(); i++) {
					String tableName = table_names_sdcch.get(i);
					map.put("table_name", tableName);
					List<SDCCH> sub_sdcchList = sdcchService.find(map);
					sdcchList.addAll(sub_sdcchList);
				}
			}
		}
		if (table_names_facch != null && table_names_facch.size() > 0) {
			map.put("start", 0);
			map.put("size", pageBean.getPageSize());
			if (increase.equals("1")) {
				for (int i = table_names_facch.size() - 1; i >= 0 && facchList.size() < pageBean.getPageSize(); i--) {
					String tableName = table_names_facch.get(i);
					map.put("table_name", tableName);
					System.out.println(map);
					List<FACCH> sub_facchList = facchService.findASC(map);
					facchList.addAll(sub_facchList);
				}
			} else {
				for (int i = 0; i < table_names_facch.size() && facchList.size() < pageBean.getPageSize(); i++) {
					String tableName = table_names_facch.get(i);
					map.put("table_name", tableName);
					List<FACCH> sub_facchList = facchService.find(map);
					facchList.addAll(sub_facchList);
				}
			}
		}

		copyProperty(sdcchList, facchList, sdcch_facchList);
		SDCCH_FACCHController.ListSort(sdcch_facchList);
		if (sdcch_facchList.size() > pageBean.getPageSize() && increase.equals("1")) {
			sdcch_facchList = sdcch_facchList.subList(0, pageBean.getPageSize());
		} else if (sdcch_facchList.size() > pageBean.getPageSize() && increase.equals("0")) {
			sdcch_facchList = sdcch_facchList.subList(sdcch_facchList.size()-pageBean.getPageSize(), sdcch_facchList.size());
		}
		
		/*
		 * 避免往前翻第一页不足100条
		 */
		if (sdcch_facchList.size() < pageBean.getPageSize() && increase.equals("0") && sdcch_facchList.size() > 0) {
			String tmptime1=sdcch_facchList.get(0).getStartTime(); 
			map.put("endTime", null);
			map.put("startTime", DateUtil.longToString(Long.parseLong(tmptime1),"yyyyMMdd"));
			table_names_sdcch = sdcchService.findTableNames(map);
			table_names_facch = facchService.findTableNames(map);
			map.put("endTime", tmptime1);
			sdcch_facchList.clear();
			sdcchList.clear();
			facchList.clear();
			if (table_names_sdcch != null) {
				map.put("start", 0);
				map.put("size", pageBean.getPageSize());
				for (int i = table_names_sdcch.size() - 1; i >= 0 && sdcchList.size() < pageBean.getPageSize(); i--) {
					map.put("table_name", table_names_sdcch.get(i));
					List<SDCCH> sub_sdcchList = sdcchService.findASC(map);
					sdcchList.addAll(sub_sdcchList);
				}
			}
			if (table_names_facch != null) {
				map.put("start", 0);
				map.put("size", pageBean.getPageSize());
				for(int i=table_names_facch.size()-1;i>=0&&facchList.size() <pageBean.getPageSize();i--){
					String tableName = table_names_facch.get(i);
					map.put("table_name", tableName);
					List<FACCH> sub_facchList = facchService.findASC(map);
					facchList.addAll(sub_facchList);
				}
			}

			copyProperty(sdcchList, facchList, sdcch_facchList);
			SDCCH_FACCHController.ListSort(sdcch_facchList);
			if (sdcch_facchList.size() > pageBean.getPageSize()) {
				sdcch_facchList = sdcch_facchList.subList(0, pageBean.getPageSize());
			}
		}
		JSONObject result = new JSONObject();
		JSONArray jsonArray = JSONArray.fromObject(sdcch_facchList);
		result.put("rows", jsonArray);
		result.put("total", Integer.MAX_VALUE);
		ResponseUtil.write(response, result);

	}

	/**
	 * 判断是否存在指定PrimaryKey
	 */
	@RequestMapping("/existPrimaryKey")
	public void existUserName(String primaryKey, HttpServletResponse response) throws Exception {
		JSONObject result = new JSONObject();
		Map<String, Object> map = new HashMap<String, Object>();
		String frontProcessorId = primaryKey.substring(0, primaryKey.indexOf("-"));
		map.put("table_name", "sdcch_" + frontProcessorId);
		map.put("PrimaryKey", primaryKey);
		if (sdcchService.findByPrimaryKey(map) == null) {
			result.put("exist", false);
		} else {
			result.put("exist", true);
		}
		ResponseUtil.write(response, result);

	}

	String headers[] = {"触发时间", "机车号", "小区名称", "BCCH", "TCH", "时隙号", "逻辑信道", "帧号", "方向", "Um接口消息类型", "Layer2类型", "公里标", "速度",
			"数据长度", "LEVEL","SNR","QUALTY","数据源码", "解码信息", "LAC", "CI", "前置机号", "记录号"};
	/**
	 * 导出SDCCH与FACCH
	 */
	@RequestMapping("/export")
	public void export(@RequestParam(value = "startTime", required = false) String startTime, @RequestParam(value = "endTime", required = false) String endTime,
			@RequestParam(value = "IMSI", required = false) String IMSI, @RequestParam(value = "MSISDN", required = false) String MSISDN,
			@RequestParam(value = "CTCS_ID", required = false) String CTCS_ID, @RequestParam(value = "UmType", required = false) String UmType,
			@RequestParam(value = "district", required = false) String district, @RequestParam(value = "kilometerStart", required = false) String kilometerStart,
			@RequestParam(value = "kilometerEnd", required = false) String kilometerEnd, @RequestParam(value = "recordId", required = false) String recordId,
			HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		Workbook wb = new HSSFWorkbook();
		String IMSI1 = "1";
		String IMSI2 = "1";
		String MSISDN1 = "1";
		String MSISDN2 = "1";
		List<String> traindata = new ArrayList<>();
		map.put("table_name", "train_info");
		if(!IMSI.equals("")) {

			map.put("IMSI", IMSI1);IMSI1 = IMSI;
			traindata = tchService.get_msisdn(map);
			if(traindata.size() != 0) {
				MSISDN1 = traindata.get(0);
			}
			CTCS_ID = "1";
		}
		else if(!MSISDN.equals("")) {
			MSISDN1 = MSISDN;
			map.put("MSISDN", MSISDN1);
			traindata = tchService.get_imsi(map);
			if(traindata.size() != 0) {
				IMSI1 = traindata.get(0);
			}
			CTCS_ID = "1";
		}
		else if(!CTCS_ID.equals("")) {
			map.put("CTCS_ID", CTCS_ID);
			traindata = tchService.get_imsi(map);
			if(traindata.size() >= 2) {
				IMSI1 = traindata.get(0);
				IMSI2 = traindata.get(1);
			}
			else if(traindata.size() == 1) {
				IMSI1 = traindata.get(0);
			}
			traindata = tchService.get_msisdn(map);
			if(traindata.size() >= 2) {
				MSISDN1 = traindata.get(0);
				MSISDN2 = traindata.get(1);
			}
			else if(traindata.size() == 1) {
				MSISDN1 = traindata.get(0);
			}
		}
		map.put("IMSI1", IMSI1);
		map.put("IMSI2", IMSI2);
		map.put("MSISDN1", MSISDN1);
		map.put("MSISDN2", MSISDN2);
		map.put("CTCS_ID", CTCS_ID);
		map.put("UmTypeAll", UmType);
		map.put("districtAll", district);
		map.put("kilometerStart", kilometerStart);
		map.put("kilometerEnd", kilometerEnd);
		
		if (StringUtil.isNotEmpty(recordId)) {
			map.put("recordId", recordId);
		}
		
		Map<String, List<String>> tables = findTableNames(UmType, startTime, endTime, district, map);
		List<String> table_names_sdcch = tables.get("table_names_sdcch");
		List<String> table_names_facch = tables.get("table_names_facch");
		
		System.out.println("tablenamesdcch="+table_names_sdcch);
		System.out.println("tablenamefacch="+table_names_facch);

		List<SDCCH_FACCH> sdcch_facchList_all = new ArrayList<SDCCH_FACCH>();

		List<SDCCH> sdcchList = new ArrayList<SDCCH>();
		List<FACCH> facchList = new ArrayList<FACCH>();
		if (table_names_sdcch != null && table_names_sdcch.size() > 0) {
			List<SDCCH> sub_sdcchList;
			map.put("start", 0);
			for (int i = table_names_sdcch.size() - 1; i >= 0 && sdcchList.size() <= ExcelUtil.maxExportRows; i--) {
				map.put("size", ExcelUtil.maxExportRows - sdcchList.size());
				map.put("table_name", table_names_sdcch.get(i));
				sub_sdcchList = sdcchService.findASC(map);
				if (sub_sdcchList != null && sub_sdcchList.size() > 0)
					sdcchList.addAll(sub_sdcchList);
			}
		}			
		if (table_names_facch != null && table_names_facch.size() > 0) {
			List<FACCH> sub_facchList;
			map.put("start", 0);
			for (int i = table_names_facch.size() - 1; i >= 0 && facchList.size() <= ExcelUtil.maxExportRows; i--) {
				map.put("size", ExcelUtil.maxExportRows - facchList.size());
				map.put("table_name", table_names_facch.get(i));
				System.out.println(map);
				sub_facchList = facchService.findASC(map);
				if (sub_facchList != null && sub_facchList.size() > 0)
					facchList.addAll(sub_facchList);
			}
		}	

		copyProperty(sdcchList, facchList, sdcch_facchList_all);
		SDCCH_FACCHController.ListSort(sdcch_facchList_all);
		if (sdcch_facchList_all.size() > ExcelUtil.maxExportRows) {
			sdcch_facchList_all = sdcch_facchList_all.subList(0, ExcelUtil.maxExportRows);
		}

		ExcelUtil.fillExcelData_SDCCH_FACCH(sdcch_facchList_all, wb, headers);
		ResponseUtil.export(response, wb, "空口信令" + FormatDate.formatDate() + ".xls");
	}
	
	
	private Map<String, List<String>> findTableNames(String UmType, String startTime, String endTime, String district, Map<String, Object> map) {
		// 当天00:00的时间戳
		Long earlyMorningTime = System.currentTimeMillis() / (1000 * 3600 * 24) * (1000 * 3600 * 24) - TimeZone.getDefault().getRawOffset();
		// 当前时间戳
		Long nowTime = System.currentTimeMillis();
		if (UmType != null && !UmType.equals("")) {
			String[] subUmType = UmType.split(",");
			List<String> subList = Arrays.asList(subUmType);
			map.put("UmType", subList);
		} else {
			map.put("UmType", "");
		}
		if (district != null && !district.equals("")) {
			String[] subdistrict = district.split(",");
			String[] frontID = new String[subdistrict.length];
			for (int i = 0; i < subdistrict.length; i++) {
				if (subdistrict[i].equals(""))
					continue;
				map.put("frontId", subdistrict[i]);
				map.put("table_name", "bs_info");
				frontID[i] = interferencequeryService.get_frontId(map);
			}
			List<String> subList = Arrays.asList(frontID);
			map.put("district", subList);
		} else {
			map.put("district", "");
		}
		if (startTime != null && !startTime.equals("NaN")) {
			map.put("startTime", DateUtil.longToString(Long.parseLong(startTime), "yyyyMMdd"));
		} else {
			map.put("startTime", DateUtil.longToString(earlyMorningTime, "yyyyMMdd"));
		}
		if (endTime != null && !endTime.equals("NaN")) {
			map.put("endTime", DateUtil.longToString(Long.parseLong(endTime), "yyyyMMdd"));
		} else {
			map.put("endTime", DateUtil.longToString(nowTime, "yyyyMMdd"));
		}

		Map<String, List<String>> tables = new HashMap<>();
		List<String> table_names_sdcch = sdcchService.findTableNames(map);
		List<String> table_names_facch = facchService.findTableNames(map);
		tables.put("table_names_sdcch", table_names_sdcch);
		tables.put("table_names_facch", table_names_facch);
		
		if (startTime != null && !startTime.equals("NaN")) {
			map.put("startTime", startTime);
		} else {
			map.put("startTime", null);
		}
		if (endTime != null && !endTime.equals("NaN")) {
			map.put("endTime", endTime);
		} else {
			map.put("endTime", null);
		}
		return tables;
	}

	/**
	 * 属性拷贝
	 */
	private void copyProperty(List<SDCCH> sdcchList, List<FACCH> facchList, List<SDCCH_FACCH> sdcch_facchList_all) {

		for(SDCCH tmp_sdcch:sdcchList){
			SDCCH_FACCH sdcch_facch = new SDCCH_FACCH();
			sdcch_facch.setChannel(tmp_sdcch.getChannel());
			sdcch_facch.setCI(tmp_sdcch.getCI());
			sdcch_facch.setCTCS_ID(tmp_sdcch.getCTCS_ID());
			sdcch_facch.setDataLength(tmp_sdcch.getDataLength());
			sdcch_facch.setDecode(tmp_sdcch.getDecode());
			sdcch_facch.setDirection(tmp_sdcch.getDirection());
			sdcch_facch.setFrontProcessorId(tmp_sdcch.getFrontProcessorId());
//			sdcch_facch.setIMSI(tmp_sdcch.getIMSI());
			if(tmp_sdcch.getL2().equals(" L2 SUB UNKNOWN")){
				sdcch_facch.setL2("");
			}else {
				sdcch_facch.setL2(tmp_sdcch.getL2());
			}
			sdcch_facch.setLAC(tmp_sdcch.getLAC());
			sdcch_facch.setLogicChannel(tmp_sdcch.getLogicChannel());
			if(tmp_sdcch.getMessage_TYPE().equals(" L2 SUB UNKNOWN")){
				continue;
			}else {
				sdcch_facch.setMessage_TYPE(tmp_sdcch.getMessage_TYPE());
			}
			sdcch_facch.setLEVEL(tmp_sdcch.getLEVEL());
			if(StringUtil.isNotEmpty(tmp_sdcch.getSNR())) {
				StringBuffer SNR=new StringBuffer();
				String[] SNRArry = tmp_sdcch.getSNR().split(" ");
				for (int i = 0; i < SNRArry.length; i++) {
					{
						double d = Double.parseDouble(SNRArry[i].trim());
						if(d>0) {
//						d=(Math.log10(d))*10;
							d = (double) Math.round(((Math.log10(d)) * 10) * 10) / 10;
							SNRArry[i] = String.valueOf((d));
//							System.out.println("SNRArry[" + i + "]:=================" + SNRArry[i]);
							SNR.append(SNRArry[i] + " ");
						}else {
							SNR.append("/ ");
						}
					}
//					System.out.println(SNR);
					sdcch_facch.setSNR(String.valueOf(SNR));
				}
			}
			sdcch_facch.setQUALITY(tmp_sdcch.getQUALITY());
//			sdcch_facch.setMS_TYPE(tmp_sdcch.getMS_TYPE());
//			sdcch_facch.setMSISDN(tmp_sdcch.getMSISDN().equals("255") ? "" : tmp_sdcch.getMSISDN());
			sdcch_facch.setRecordId(tmp_sdcch.getRecordId());
			sdcch_facch.setSiteName(tmp_sdcch.getSiteName());
			sdcch_facch.setSourceData(tmp_sdcch.getSourceData());
			sdcch_facch.setStartTime(tmp_sdcch.getTimeStamp());
			sdcch_facch.setTCH(tmp_sdcch.getTCH());
			sdcch_facch.setTimeSlot(tmp_sdcch.getTimeSlot());
//			sdcch_facch.setTMSI(tmp_sdcch.getTMSI());
			sdcch_facch.setFrameNumber(tmp_sdcch.getFrameNumber());
			sdcch_facch.setKilometer(tmp_sdcch.getKilometer());
			sdcch_facch.setBCCH(tmp_sdcch.getBCCH());
			sdcch_facch.setSpeed(tmp_sdcch.getSpeed());
			sdcch_facch.setPrimaryKey(tmp_sdcch.getPrimaryKey());
			sdcch_facchList_all.add(sdcch_facch);
		}
		for(FACCH tmp_facch:facchList){
			SDCCH_FACCH sdcch_facch = new SDCCH_FACCH();
			sdcch_facch.setChannel(tmp_facch.getChannel());
			sdcch_facch.setCI(tmp_facch.getCI());
			sdcch_facch.setCTCS_ID(tmp_facch.getCTCS_ID());
			sdcch_facch.setDataLength(tmp_facch.getDataLength());
			sdcch_facch.setDecode(tmp_facch.getDecode());
			sdcch_facch.setDirection(tmp_facch.getDirection());
			sdcch_facch.setFrontProcessorId(tmp_facch.getFrontProcessorId());
//			sdcch_facch.setIMSI(tmp_facch.getIMSI());
			if(tmp_facch.getL2().equals(" L2 SUB UNKNOWN")){
				sdcch_facch.setL2("");
			}else {
				sdcch_facch.setL2(tmp_facch.getL2());
			}
			sdcch_facch.setLAC(tmp_facch.getLAC());
			sdcch_facch.setLogicChannel(tmp_facch.getLogicChannel());
//			sdcch_facch.setMessage_TYPE(tmp_facch.getMessage_TYPE());
			if(tmp_facch.getMessage_TYPE().equals(" L2 SUB UNKNOWN")){
				continue;
			}else {
				sdcch_facch.setMessage_TYPE(tmp_facch.getMessage_TYPE());
			}
			sdcch_facch.setLEVEL(tmp_facch.getLEVEL());
//			sdcch_facch.setSNR(tmp_facch.getSNR());
			if(StringUtil.isNotEmpty(tmp_facch.getSNR())) {
				StringBuffer SNR=new StringBuffer();
				String[] SNRArry = tmp_facch.getSNR().split(" ");
				for (int i = 0; i < SNRArry.length; i++) {
					{
						double d = Double.parseDouble(SNRArry[i].trim());
						if(d>0) {
//						d=(Math.log10(d))*10;
							d = (double) Math.round(((Math.log10(d)) * 10) * 10) / 10;
							SNRArry[i] = String.valueOf((d));
//							System.out.println("SNRArry[" + i + "]:=================" + SNRArry[i]);
							SNR.append(SNRArry[i] + " ");
						}else {
							SNR.append("/ ");
						}
					}
//					System.out.println(SNR);
					sdcch_facch.setSNR(String.valueOf(SNR));
				}
			}
			sdcch_facch.setQUALITY(tmp_facch.getQUALITY());
//			sdcch_facch.setMS_TYPE(tmp_facch.getMS_TYPE());
//			sdcch_facch.setMSISDN(tmp_facch.getMSISDN().equals("255") ? "" : tmp_facch.getMSISDN());
			sdcch_facch.setRecordId(tmp_facch.getRecordId());
			sdcch_facch.setSiteName(tmp_facch.getSiteName());
			sdcch_facch.setSourceData(tmp_facch.getSourceData());
			sdcch_facch.setStartTime(tmp_facch.getTimeStamp());
			sdcch_facch.setTCH(tmp_facch.getTCH());
			sdcch_facch.setTimeSlot(tmp_facch.getTimeSlot());
//			sdcch_facch.setTMSI(tmp_facch.getTMSI());
			sdcch_facch.setFrameNumber(tmp_facch.getFrameNumber());
			sdcch_facch.setKilometer(tmp_facch.getKilometer());
			sdcch_facch.setBCCH(tmp_facch.getS_ARFCN());
			sdcch_facch.setSpeed(tmp_facch.getSpeed());
			sdcch_facch.setPrimaryKey(tmp_facch.getPrimaryKey());
			sdcch_facchList_all.add(sdcch_facch);
		}
	}

	/**
	 * 导出当前页的数据
	 */
	@RequestMapping("/exportcurrentpage")
	public void exportcurrentpage(@RequestParam(value = "data") String data, HttpServletResponse response) throws Exception {
		Workbook wb = new HSSFWorkbook();
		
		List<SDCCH_FACCH> sdcch_facchList_all = new ArrayList<SDCCH_FACCH>();
		if(data != null && !data.equals("null") && !data.equals("")) {
			JSONArray jsonArray=JSONArray.fromObject(data); 
			for(int i =0; i<jsonArray.size();i++) {
				SDCCH_FACCH sdcch_facch = new SDCCH_FACCH();

				sdcch_facch.setFrameNumber(jsonArray.getJSONObject(i).getString("frameNumber"));
				sdcch_facch.setKilometer(jsonArray.getJSONObject(i).getString("kilometer"));
				sdcch_facch.setSpeed(jsonArray.getJSONObject(i).getString("speed"));
				sdcch_facch.setBCCH(jsonArray.getJSONObject(i).getString("BCCH"));
				sdcch_facch.setCI(jsonArray.getJSONObject(i).getString("CI"));
				sdcch_facch.setCTCS_ID(jsonArray.getJSONObject(i).getString("CTCS_ID"));
				sdcch_facch.setDataLength(jsonArray.getJSONObject(i).getString("dataLength"));
				sdcch_facch.setDecode(jsonArray.getJSONObject(i).getString("decode"));
				sdcch_facch.setDirection(jsonArray.getJSONObject(i).getString("direction"));
				sdcch_facch.setFrontProcessorId(jsonArray.getJSONObject(i).getString("frontProcessorId"));
				sdcch_facch.setIMSI(jsonArray.getJSONObject(i).getString("IMSI"));
				sdcch_facch.setL2(jsonArray.getJSONObject(i).getString("l2"));
				sdcch_facch.setLAC(jsonArray.getJSONObject(i).getString("LAC"));
				sdcch_facch.setLogicChannel(jsonArray.getJSONObject(i).getString("logicChannel"));
				sdcch_facch.setMessage_TYPE(jsonArray.getJSONObject(i).getString("message_TYPE"));
				sdcch_facch.setMS_TYPE(jsonArray.getJSONObject(i).getString("MS_TYPE"));
				sdcch_facch.setLEVEL(jsonArray.getJSONObject(i).getString("LEVEL"));
				sdcch_facch.setSNR(jsonArray.getJSONObject(i).getString("SNR"));
				sdcch_facch.setQUALITY(jsonArray.getJSONObject(i).getString("QUALITY"));
				sdcch_facch.setMSISDN(jsonArray.getJSONObject(i).getString("MSISDN").equals("255") ? "" : jsonArray.getJSONObject(i).getString("MSISDN"));
				sdcch_facch.setRecordId(jsonArray.getJSONObject(i).getString("recordId"));
				sdcch_facch.setSiteName(jsonArray.getJSONObject(i).getString("siteName"));
				sdcch_facch.setSourceData(jsonArray.getJSONObject(i).getString("sourceData"));
				sdcch_facch.setStartTime(jsonArray.getJSONObject(i).getString("startTime"));
				sdcch_facch.setTCH(jsonArray.getJSONObject(i).getString("TCH"));
				sdcch_facch.setTimeSlot(jsonArray.getJSONObject(i).getString("timeSlot"));
				sdcch_facch.setTMSI(jsonArray.getJSONObject(i).getString("TMSI"));
				sdcch_facch.setChannel(jsonArray.getJSONObject(i).getString("channel"));
				sdcch_facchList_all.add(sdcch_facch);
			}
		}
		SDCCH_FACCHController.ListSort(sdcch_facchList_all);
		ExcelUtil.fillExcelData_SDCCH_FACCH(sdcch_facchList_all, wb, headers);
		ResponseUtil.export(response, wb, "空口信令" + FormatDate.formatDate() + ".xls");
	}


	/**
	 * 用模板导出用户
	 */
	@RequestMapping("/exportByTemplate")
	public void exportByTemplate(@RequestParam(value = "ids") String ids, HttpServletResponse response)
			throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		List<SDCCH> sdcchList = new ArrayList<SDCCH>();
		List<FACCH> facchList = new ArrayList<FACCH>();
		if (ids != null && !ids.equals("null") && !ids.equals("")) {
			SDCCH_FACCHController.ListSort(sdcch_facchList);
			
			try {
				Workbook wb=ExcelUtil.fillExcelDataWithTemplate_SDCCH_FACCH(sdcch_facchList,"sdcch_facchExportTemplate.xls");
				ResponseUtil.export(response, wb, "模版导出excel"+FormatDate.formatDate()+".xls");
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			sdcchList.clear();
			List<SDCCH> sub_sdcchList = null;
			List<String> table_names = sdcchService.findTableNames(map);
			if (table_names != null) {
				for (int i = 0; i < table_names.size(); i++) {
					sub_sdcchList = null;
					map.put("table_name", table_names.get(i));
					sub_sdcchList = sdcchService.find(map);
					if (sub_sdcchList != null) {
						sdcchList.addAll(sub_sdcchList);
					}

				}
			}
			
			facchList.clear();
			List<FACCH> sub_facchList = null;
			List<String> table_names_facch = facchService.findTableNames(map);
			if (table_names_facch != null) {
				for (int i = 0; i < table_names_facch.size(); i++) {
					sub_facchList = null;
					map.put("table_name", table_names_facch.get(i));
					sub_facchList = facchService.find(map);
					if (sub_facchList != null) {
						facchList.addAll(sub_facchList);
					}

				}
			}
			
			for(SDCCH tmp_sdcch:sdcchList){
				SDCCH_FACCH sdcch_facch = new SDCCH_FACCH();
				sdcch_facch.setChannel(tmp_sdcch.getChannel());
				sdcch_facch.setCI(tmp_sdcch.getCI());
				sdcch_facch.setCTCS_ID(tmp_sdcch.getCTCS_ID());
				sdcch_facch.setDataLength(tmp_sdcch.getDataLength());
				sdcch_facch.setDecode(tmp_sdcch.getDecode());
				sdcch_facch.setDirection(tmp_sdcch.getDirection());
				sdcch_facch.setFrontProcessorId(tmp_sdcch.getFrontProcessorId());
				sdcch_facch.setIMSI(tmp_sdcch.getIMSI());
				sdcch_facch.setL2(tmp_sdcch.getL2());
				sdcch_facch.setLAC(tmp_sdcch.getLAC());
				sdcch_facch.setLogicChannel(tmp_sdcch.getLogicChannel());
				sdcch_facch.setMessage_TYPE(tmp_sdcch.getMessage_TYPE());
				sdcch_facch.setMS_TYPE(tmp_sdcch.getMS_TYPE());
				sdcch_facch.setMSISDN(tmp_sdcch.getMSISDN().equals("255") ? "" : tmp_sdcch.getMSISDN());
				sdcch_facch.setRecordId(tmp_sdcch.getRecordId());
				sdcch_facch.setSiteName(tmp_sdcch.getSiteName());
				sdcch_facch.setSourceData(tmp_sdcch.getSourceData());
				sdcch_facch.setStartTime(tmp_sdcch.getStartTime());
				sdcch_facch.setTCH(tmp_sdcch.getTCH());
				sdcch_facch.setTimeSlot(tmp_sdcch.getTimeSlot());
				sdcch_facch.setTMSI(tmp_sdcch.getTMSI());
				sdcch_facchList.add(sdcch_facch);
			}
			for(FACCH tmp_facch:facchList){
				SDCCH_FACCH sdcch_facch = new SDCCH_FACCH();
				sdcch_facch.setChannel(tmp_facch.getChannel());
				sdcch_facch.setCI(tmp_facch.getCI());
				sdcch_facch.setCTCS_ID(tmp_facch.getCTCS_ID());
				sdcch_facch.setDataLength(tmp_facch.getDataLength());
				sdcch_facch.setDecode(tmp_facch.getDecode());
				sdcch_facch.setDirection(tmp_facch.getDirection());
				sdcch_facch.setFrontProcessorId(tmp_facch.getFrontProcessorId());
				sdcch_facch.setIMSI(tmp_facch.getIMSI());
				sdcch_facch.setL2(tmp_facch.getL2());
				sdcch_facch.setLAC(tmp_facch.getLAC());
				sdcch_facch.setLogicChannel(tmp_facch.getLogicChannel());
				sdcch_facch.setMessage_TYPE(tmp_facch.getMessage_TYPE());
				sdcch_facch.setMS_TYPE(tmp_facch.getMS_TYPE());
				sdcch_facch.setMSISDN(tmp_facch.getMSISDN().equals("255") ? "" : tmp_facch.getMSISDN());
				sdcch_facch.setRecordId(tmp_facch.getRecordId());
				sdcch_facch.setSiteName(tmp_facch.getSiteName());
				sdcch_facch.setSourceData(tmp_facch.getSourceData());
				sdcch_facch.setStartTime(tmp_facch.getStartTime());
				sdcch_facch.setTCH(tmp_facch.getTCH());
				sdcch_facch.setTimeSlot(tmp_facch.getTimeSlot());
				sdcch_facch.setTMSI(tmp_facch.getTMSI());
				sdcch_facchList.add(sdcch_facch);
			}
			
			SDCCH_FACCHController.ListSort(sdcch_facchList);
			
			try {
				Workbook wb=ExcelUtil.fillExcelDataWithTemplate_SDCCH_FACCH(sdcch_facchList,"sdcch_facchExportTemplate.xls");
				ResponseUtil.export(response, wb, "利用模版导出excel"+FormatDate.formatDate()+".xls");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

	/**
	 * 查找District列表
	 * 
	 * @param
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/sdcchDistrictComboList")
	public void sdcchDistrictComboList(HttpServletResponse response) throws Exception {
		Map<String,Object> map=new HashMap<String,Object>();
		JSONArray jsonArray=new JSONArray();
		JSONObject jsonObject=new JSONObject();
		jsonObject.put("id", -1);
		jsonObject.put("name", "");
		jsonArray.add(jsonObject);
		map.put("table_name","bs_info");
		List<String> bs_names=sdcchService.findDistricts(map);
		for(int i=0;i<bs_names.size();i++)
		{
			jsonObject.put("id", i);
			jsonObject.put("name",bs_names.get(i));
			jsonArray.add(jsonObject);
			
		}
		ResponseUtil.write(response, jsonArray);

	}

	/**
	 * 查找Message_TYPE列表
	 */
	@RequestMapping("/sdcchMessage_TYPEComboList")
	public void sdcchMessage_TYPEComboList(HttpServletResponse response) throws Exception {
		JSONArray jsonArray = new JSONArray();
		Map<String, Object> map = new HashMap<String, Object>();
		List<String> table_names = sdcchService.findTableNames(map);
		List<SDCCH> sdcchList = new ArrayList<SDCCH>();
		if (table_names != null) {
			for (int i = 0; i < table_names.size(); i++) {
				map.put("table_name", table_names.get(i));
				List<SDCCH> sub_sdcchList = sdcchService.findMessage_TYPEs(map);
				sdcchList.addAll(sub_sdcchList);
			}
		}
		
		// 过滤重复的Message_TYPE
		Map message_TYPE_map = new HashMap<>();
		for (int i = 0; i < sdcchList.size(); i++) {
			message_TYPE_map.put(sdcchList.get(i).getMessage_TYPE(), 1);
		}
		Iterator<Map.Entry<String, String>> iterator = message_TYPE_map.entrySet().iterator();
		sdcchList.clear();
		while (iterator.hasNext()) {
			Map.Entry<String, String> entry = iterator.next();
			SDCCH sdcch = new SDCCH();
			sdcch.setMessage_TYPE(entry.getKey());
			sdcchList.add(sdcch);
		}
				
		JSONArray rows = JSONArray.fromObject(sdcchList);
		jsonArray.addAll(rows);
		ResponseUtil.write(response, jsonArray);
	}

	/**
	 * 查找前置机列表
	 */
	@RequestMapping("/sdcchFrontProcessorIdComboList")
	public void sdcchFrontProcessorIdComboList(HttpServletResponse response) throws Exception {
		Map<String,Object> map=new HashMap<String,Object>();
		JSONArray jsonArray=new JSONArray();
		JSONObject jsonObject=new JSONObject();
		jsonObject.put("id", -1);
		jsonObject.put("name", "");
		jsonArray.add(jsonObject);
		map.put("table_name","bs_info");
		List<String> FrontProcessorIds=sdcchService.findFrontProcessorIds(map);
		for(int i=0;i<FrontProcessorIds.size();i++)
		{
			jsonObject.put("id", i);
			jsonObject.put("name",FrontProcessorIds.get(i));
			jsonArray.add(jsonObject);
			
		}
		ResponseUtil.write(response, jsonArray);
	}

	/**
	 * 查找IMSI列表
	 */
	@RequestMapping("/sdcchIMSIComboList")
	public void sdcchIMSIComboList(HttpServletResponse response) throws Exception {
		JSONArray jsonArray = new JSONArray();
		Map<String, Object> map = new HashMap<String, Object>();
		List<String> table_names = sdcchService.findTableNames(map);
		List<SDCCH> sdcchList = new ArrayList<SDCCH>();
		if (table_names != null) {
			for (int i = 0; i < table_names.size(); i++) {
				map.put("table_name", table_names.get(i));
				List<SDCCH> sub_sdcchList = sdcchService.findIMSIs(map);
				sdcchList.addAll(sub_sdcchList);
			}
		}
		
		// 过滤重复的IMSI
		Map iMSI_map = new HashMap<>();
		for (int i = 0; i < sdcchList.size(); i++) {
			iMSI_map.put(sdcchList.get(i).getIMSI(), 1);
		}
		Iterator<Map.Entry<String, String>> iterator = iMSI_map.entrySet().iterator();
		sdcchList.clear();
		while (iterator.hasNext()) {
			Map.Entry<String, String> entry = iterator.next();
			SDCCH sdcch = new SDCCH();
			sdcch.setIMSI(entry.getKey());
			sdcchList.add(sdcch);
		}
				
		JSONArray rows = JSONArray.fromObject(sdcchList);
		jsonArray.addAll(rows);
		ResponseUtil.write(response, jsonArray);

	}

	/**
	 * 查找MSISDN列表
	 */
	@RequestMapping("/sdcchMSISDNComboList")
	public void sdcchMSISDNComboList(HttpServletResponse response) throws Exception {
		JSONArray jsonArray = new JSONArray();
		Map<String, Object> map = new HashMap<String, Object>();
		List<String> table_names = sdcchService.findTableNames(map);
		List<SDCCH> sdcchList = new ArrayList<SDCCH>();
		if (table_names != null) {
			for (int i = 0; i < table_names.size(); i++) {
				map.put("table_name", table_names.get(i));
				List<SDCCH> sub_sdcchList = sdcchService.findMSISDNs(map);
				if (sub_sdcchList != null && sub_sdcchList.size() > 0) sdcchList.addAll(sub_sdcchList);
			}
		}
		
		// 过滤重复的MSISDN
		Map mSISDN_map = new HashMap<>();
		for (int i = 0; i < sdcchList.size(); i++) {
			mSISDN_map.put(sdcchList.get(i).getMSISDN().equals("255") ? "" : sdcchList.get(i).getMSISDN(), 1);
		}
		Iterator<Map.Entry<String, String>> iterator = mSISDN_map.entrySet().iterator();
		sdcchList.clear();
		while (iterator.hasNext()) {
			Map.Entry<String, String> entry = iterator.next();
			SDCCH sdcch = new SDCCH();
			sdcch.setMSISDN(entry.getKey());
			sdcchList.add(sdcch);
		}
				
		JSONArray rows = JSONArray.fromObject(sdcchList);
		jsonArray.addAll(rows);
		ResponseUtil.write(response, jsonArray);

	}

	/**
	 * 查找CTCS_ID列表
	 */
	@RequestMapping("/sdcchCTCS_IDComboList")
	public void sdcchCTCS_IDComboList(HttpServletResponse response) throws Exception {
		JSONArray jsonArray = new JSONArray();
		Map<String, Object> map = new HashMap<String, Object>();
		List<String> table_names = sdcchService.findTableNames(map);
		List<SDCCH> sdcchList = new ArrayList<SDCCH>();
		if (table_names != null) {
			for (int i = 0; i < table_names.size(); i++) {
				map.put("table_name", table_names.get(i));
				List<SDCCH> sub_sdcchList = sdcchService.findCTCS_IDs(map);
				sdcchList.addAll(sub_sdcchList);
			}
		}
		
		// 过滤重复的CTCS_ID
		Map cTCS_ID_map = new HashMap<>();
		for (int i = 0; i < sdcchList.size(); i++) {
			cTCS_ID_map.put(sdcchList.get(i).getCTCS_ID(), 1);
		}
		Iterator<Map.Entry<String, String>> iterator = cTCS_ID_map.entrySet().iterator();
		sdcchList.clear();
		while (iterator.hasNext()) {
			Map.Entry<String, String> entry = iterator.next();
			SDCCH sdcch = new SDCCH();
			sdcch.setCTCS_ID(entry.getKey());
			sdcchList.add(sdcch);
		}
				
		JSONArray rows = JSONArray.fromObject(sdcchList);
		jsonArray.addAll(rows);
		ResponseUtil.write(response, jsonArray);

	}
	
	/**
	 * 对List中每个对象元素升序排序 
	 */
	private static void ListSort(List<SDCCH_FACCH> list) {
		if (list == null || list.size() < 2)
			return;
		Collections.sort(list, new Comparator<SDCCH_FACCH>() {
			@Override
			public int compare(SDCCH_FACCH sf1, SDCCH_FACCH sf2) {
				try {
					Long l1 = Long.parseLong(sf1.getStartTime());
					Long l2 = Long.parseLong(sf2.getStartTime());
					if (l1 < l2) {
						return -1;
					} else if (l1 > l2) {
						return 1;
					} else {
						return 0;
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				return 0;
			}
		});
	}
}